import React, {Component} from 'react';

import './index.less';

import {
    base,
    toast,
    getMultiLang
} from 'nc-lightapp-front';

import getBatchTemplateData from './getBatchTemplateData';
import getInfoItemTemplate from './getBatchEditInfoItemTemplate';
import getBatchValueTemplate from './getBatchValueTemplate';
import submitBatchEdit from './submitBatchEdit';

import getLanguage from '../../language';

const {
    NCModal,
    NCButton
} = base;

const {
    Header: NCModalHeader,
    Body: NCModalBody,
    Footer: NCModalFooter
} = NCModal;

const batchEdit = 'batch_edit';

class BatchEdit extends Component {
    constructor(props) {
        super(props);

        this.state = {
            infoSetSelected: {},
            infoItemSelected: {},
            language: {}
        };

        this.closeModal = this.closeModal.bind(this);
        this.getBatchTemplateData = this.getBatchTemplateData.bind(this);
        this.onEntered = this.onEntered.bind(this);
        this.editHandle = this.editHandle.bind(this);
        this.editInfoSetHandle = this.editInfoSetHandle.bind(this);
        this.editInfoItemHandle = this.editInfoItemHandle.bind(this);
        this.submitBatchEdit = this.submitBatchEdit.bind(this);
    }

    async submitBatchEdit() {
        let isPassedCheck = this.props.form.isCheckNow(batchEdit);

        if(isPassedCheck) {
            let postData = {
                param_str: [],
                pk_org: this.props.humanResourceOrganizationValue.refpk,
                model: {
                    rows: [{
                        values: {}
                    }]
                }
            };

            let values = this.props.form.getAllFormValue(batchEdit);

            this.props.selectedRows && this.props.selectedRows.map((item) => {
                postData['param_str'].push(item.data.values['pk_psnjob'].value);
            });

            postData['model'] = values;

            try {
                let res = await submitBatchEdit(postData);

                if(res.success) {
                    this.closeModal();
                    toast({
                        color: 'success',
                        content: this.state.language['hi6007-000041']/* 国际化处理： 修改成功*/
                    });
                }
            }
            catch(e) {

            }
        }
    }

    editHandle(props, moduleId, field, value) {
        if(field === 'table') {
            this.editInfoSetHandle(field, value);
        }
        else if(field === 'field') {
            this.editInfoItemHandle(field, value);
        }
    }

    // 信息项修改
    async editInfoItemHandle(field, value) {
        let postData = {
            func_type: this.props.func_type,
            pk_org: this.props.humanResourceOrganizationValue.refpk,
            table_code: this.state.infoSetSelected.value,
            field_code: value.value
        };

        try {
            let res = await getBatchValueTemplate(postData);
            let meta = this.props.meta.getMeta();

            // 因为接口返回的数据对于前两个下拉框的选项数据没有填充，
            // 所以用原数据保持下拉框选项数据不变
            res.data['items'][0] = meta[batchEdit]['items'][0];
            res.data['items'][1] = meta[batchEdit]['items'][1];

            this.props.form.setFormItemsValue(batchEdit, {
                value: {
                    display: '',
                    value: ''
                }
            });

            this.updateBatchEditTemplate(res.data);
        }
        catch(e) {

        }
    }

    // 信息集修改触发
    async editInfoSetHandle(field, value) {
        let postData = {
            func_type: this.props.func_type,
            pk_org: this.props.humanResourceOrganizationValue.refpk,
            table_code: value.value
        };

        this.setState({
            infoSetSelected: value
        });

        try {
            let res = await getInfoItemTemplate(postData);
            let meta = this.props.meta.getMeta();

            // 因为接口返回的数据对于前一个下拉框选项的数据没有填充，
            // 所以用原数据保持下拉框选项数据不变
            res.data['items'][0] = meta[batchEdit]['items'][0];

            // 选择信息集的时候，清空信息项和值
            if(field === 'table') {
                this.props.form.setFormItemsValue(batchEdit, {
                    field: {
                        display: '',
                        value: ''
                    },
                    value: {
                        display: '',
                        value: ''
                    }
                });
            }
            
            this.updateBatchEditTemplate(res.data);
        }
        catch(e) {

        }
    }

    onEntered() {
        this.props.form.setFormStatus(batchEdit, 'edit');
    }

    closeModal() {
        this.props.updateState({
            batchEditModalVisible: false
        }, () => {
            this.props.form.EmptyAllFormValue(batchEdit);
        });
    }

    updateBatchEditTemplate(data) {
        const {
            meta: {
                getMeta,
                setMeta
            },
            form: {
                setFormStatus
            }
        } = this.props;
        let meta = getMeta();

        data.items.map((item) => {
            if(!('attrcode' in item) && 'code' in item) {
                item.attrcode = item.code;
            }
            // if(item.itemtype === 'datePickerNoTimeZone') {
            //     item.itemtype = 'datepicker';
            // }
        });

        meta[batchEdit] = data;
        setMeta(meta);
        setFormStatus(batchEdit, 'edit');
    }

    async getBatchTemplateData() {

        let postData = {
            func_type: this.props.func_type,
            param_str: [],
            pk_org: this.props.humanResourceOrganizationValue.refpk
        };
        this.props.selectedRows && this.props.selectedRows.map((item) => {
            postData['param_str'].push(item.data.values['pk_psnjob'].value);
        });

        try {
            let res = await getBatchTemplateData(postData);

            this.updateBatchEditTemplate(res.data);

            this.props.updateState({
                batchEditModalVisible: true
            });
        }
        catch(e) {
        }
    }

    componentDidMount() {
        setTimeout(() => {
            this.props.MultiInit.getMultiLang({
                moduleId: 'p6007',
                domainName: 'hrhi',
                callback: (json, status, inlt) => {
                    this.setState({
                        language: json
                    });
                }
            });
        }, 1000);
    }

    render() {
        const {
            batchEditModalVisible,
            form
        } = this.props;

        const {
            language
        } = this.state;

        return (
            <NCModal
                show={batchEditModalVisible}
                onHide={this.closeModal}
                className="batch-edit-modal"
                onEntered={this.onEntered}
                size="sm"
                backdrop="static"
            >
                <NCModalHeader
                    closeButton={true}
                >
                    {language['hi6007-000040']}{/* 国际化处理： 批量修改*/}
                </NCModalHeader>
                <NCModalBody>
                    <div className="batch-edit-content">
                        {form.createForm(batchEdit, {
                            onAfterEvent: this.editHandle
                        })}
                    </div>
                </NCModalBody>
                <NCModalFooter>
                    <NCButton
                        colors="primary"
                        onClick={this.submitBatchEdit}
                    >
                        {language['hi6007-000002']}{/* 国际化处理： 确定*/}
                    </NCButton>
                    <NCButton
                        onClick={this.closeModal}
                    >
                        {language['hi6007-000003']}{/* 国际化处理： 取消*/}
                    </NCButton>
                </NCModalFooter>
            </NCModal>
        );
    }
}

export default BatchEdit;
